const App = {
    // mixins: [Query],//配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            Data: [],
            showDialog: false,
            form: {},
            nodeKey: '',
            websocket: null,
            village_activities: {},
            multipleSelection: [],
            is: true,
            relativePath: '',
            isPoints: false,
            showDialog1: false,
            personal_points_change_log_attachment: [],
            fileList: [],
            isDK:false
        }
    },
    mounted() {
        // this.submitSave();
        let ls_URL = window.location.href;
        this.relativePath = ls_URL.substring(
            ls_URL.lastIndexOf("view"),
            ls_URL.length
        );
        this.nodeKey = getQueryObject(ls_URL, "nodeKey");// 获取 nodeKey 参数
        this.handleShow(this.nodeKey);
    },
    methods: {
        // submitSave() {
        //     this.websocket = new WebSocketClient();
        //     this.websocket.init({
        //         url: `${ws}/generalSave/${getCookie('token')}`,
        //         onmessage: (data) => {
        //             try {
        //                 const res = JSON.parse(data);
        //                 if (res.REDIRECT && res.REDIRECT == 'REDIRECT') {//重定向
        //                     removeCookie("token");
        //                     removeCookie("user");
        //                     sessionStorage.setItem("REDIRECT", "登录已过期，请重新登录！");
        //                     window.parent.document.location.href = absolutepath() + res.CONTENTPATH;
        //                 } else {
        //                     if (res.Action == 'QianDao') {//签到
        //                         if (res.Status == 'success') {
        //                             this.handleShow(this.nodeKey);
        //                             this.form.Check_In_Datetime = '';
        //                             this.showDialog = false;
        //                         }
        //                     } else if (res.Action == 'BatchPoints') {//批量分配积分
        //                         if (res.Status == 'success') {
        //                             this.$refs.multipleTable.clearSelection();
        //                             this.isPoints = false;
        //                             if (this.$refs.ylUpload) {
        //                                 this.$refs.ylUpload.handleClear();
        //                             }
        //                             this.personal_points_change_log_attachment = [];
        //                             this.showDialog1 = false;
        //                             this.handleShow(this.nodeKey);
        //                         } else {
        //                             this.$message({
        //                                 type: 'error',
        //                                 message: '操作失败'
        //                             });
        //                         }
        //                     }
        //                 }
        //             } catch (error) { }
        //         },
        //     })
        //     window.addEventListener("beforeunload", () => {
        //         this.websocket.close();
        //     });
        // },
        handle(row) {
            if (!this.isDK) {
                this.$message({
                    type: 'warning',
                    message: '活动未开始'
                });  
                return 
            }
            this.form = {};
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                method: "post",
                data: {
                    Data: JSON.stringify([{
                        tableName: 'village_activities_members',
                        Condition: window.btoa(unescape(encodeURIComponent(`Village_Activity_Member_SerialNumber='${row.Village_Activity_Member_SerialNumber}'`))),
                    }, {
                        tableName: 'village_activities',
                        Condition: window.btoa(unescape(encodeURIComponent(`Village_Activity_SerialNumber='${row.Village_Activity_SerialNumber}'`))),
                    }])
                },
                success: ({ village_activities_members, village_activities }) => {
                    this.village_activities = village_activities[0];
                    this.form = village_activities_members[0];
                    this.showDialog = true;
                    this.is = true;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });
        },
        async validateAllForms() {
            //获取当前页面上所有的Elform
            let forms = [];
            for (let key in this.$refs) {
                const ref = this.$refs[key];
                if (ref.$options && ref.$options.name == 'ElForm') {
                    forms.push(ref);
                }
            }
            //判断每个Elform的校验是否通过
            let isfail = false;
            for (const form of forms) {
                try {
                    await form.validate();
                } catch (error) {
                    isfail = true;
                }
            }
            if (isfail) {
                return false;
            }
            return true;
        },
        batchPoints() {
            this.$refs.multipleTable.clearSelection();
            this.isPoints = !this.isPoints;
        },
        success(row, res) {
            this.personal_points_change_log_attachment.push({
                uid: row.uid,
                Attachment_URL: res.fileName,
                Attachment_Name: row.name,
                Temp_Path: res.tempPath,
            })
        },
        remove(row) {
            this.personal_points_change_log_attachment = this.personal_points_change_log_attachment.filter(i => i.uid != row.uid);
        },
        handleBatchPoints(is, row = false) {
            if (is == '1') {
                if (row) {//单条
                    this.multipleSelection.push(row);
                    this.isPoints = false;
                }
                if (this.multipleSelection.length == 0) {
                    this.$message({
                        type: 'warning',
                        message: '请选择发放（取消发放）积分的人员'
                    });
                    return
                }
                this.showDialog1 = true;
            } else {
                if (row) {//单条
                    this.multipleSelection.push(row);
                    this.isPoints = false;
                    this.submitBatchPoints(is)
                }
            }
        },
        submitBatchPoints(is) {
            if (is == '1') {
                let str1 = this.multipleSelection.map(i => `'${i.Village_Activity_Member_SerialNumber}'`).join(',');
                let str2 = this.multipleSelection.map(i => `'${i.ID_Card_Number}'`).join(',');
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                    method: "post",
                    data: {
                        Data: JSON.stringify([{
                            tableName: 'village_activities_members',
                            Condition: window.btoa(unescape(encodeURIComponent(`Village_Activity_Member_SerialNumber IN (${str1})`))),
                        }, {
                            tableName: 'personal_points_account',
                            Condition: window.btoa(unescape(encodeURIComponent(`ID_Card_Number IN (${str2}) AND Points_Type='0'`))),
                        }]),
                    },
                    success: ({ village_activities_members, personal_points_account }) => {
                        if (village_activities_members.length > 0) {
                            village_activities_members.forEach(item => {
                                item.isPoints = is
                            })
                            let news_personal_points_account = [], personal_points_change_log = [];
                            this.multipleSelection.forEach(row => {
                                let obj = personal_points_account.filter(i => i.ID_Card_Number == row.ID_Card_Number)[0];
                                let Remain_Points = '0';
                                if (obj) {//拥有积分账户
                                    obj.Remain_Points = accAdd(obj.Remain_Points, row.Activity_Points);
                                    obj.Total_Points = accAdd(obj.Total_Points, row.Activity_Points);
                                    Remain_Points = obj.Remain_Points;
                                } else {//没有积分账户
                                    news_personal_points_account.push({
                                        ID_Card_Number: row.ID_Card_Number,
                                        Points_Type: '0',
                                        Total_Points: row.Activity_Points,
                                        Remain_Points: row.Activity_Points,
                                    })
                                    Remain_Points = row.Activity_Points;
                                }
                                personal_points_change_log.push({
                                    ID_Card_Number: row.ID_Card_Number,
                                    Points_Title: '增加村民积分',
                                    Points_Type: '0',
                                    Object_SerialNumber: row.Village_Activity_SerialNumber,
                                    Change_Points: row.Activity_Points,
                                    Remain_Points,
                                    Notes: '增加村民积分',
                                    Children: {
                                        personal_points_change_log_attachment: this.personal_points_change_log_attachment
                                    }
                                })
                            })
                            let lJSONObject_DataSet = {
                                Modify: {
                                    village_activities_members,
                                    personal_points_account
                                },
                                Add: {
                                    personal_points_account: news_personal_points_account,
                                    personal_points_change_log
                                }
                            };
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSave",
                                Operation_IP: getIpAddress()
                            }]

                            // $.ajax({
                            //     headers: requestHeaders("JSON"),
                            //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                            //     method: "post",
                            //     data: JSON.stringify({
                            //         Data: lJSONObject_DataSet,
                            //     }),
                            //     success: (res) => {
                            //         if (res.Status == 'success') {
                            //             this.$refs.multipleTable.clearSelection();
                            //             this.isPoints = false;
                            //             if (this.$refs.ylUpload) {
                            //                 this.$refs.ylUpload.handleClear();
                            //             }
                            //             this.personal_points_change_log_attachment = [];
                            //             this.showDialog1 = false;
                            //             this.handleShow(this.nodeKey);
                            //         } else {
                            //             this.$message({
                            //                 type: 'error',
                            //                 message: '操作失败'
                            //             });
                            //         }
                            //     },
                            //     complete: (XMLHttpRequest) => {
                            //         this.loading = false;
                            //         requestPretreatment(XMLHttpRequest)
                            //     }
                            // });

                            // console.log(JSON.stringify(lJSONObject_DataSet));
                            submitSave(lJSONObject_DataSet,(res)=>{
                                if (res.Status == 'success') {
                                    this.$refs.multipleTable.clearSelection();
                                    this.isPoints = false;
                                    if (this.$refs.ylUpload) {
                                        this.$refs.ylUpload.handleClear();
                                    }
                                    this.personal_points_change_log_attachment = [];
                                    this.showDialog1 = false;
                                    this.handleShow(this.nodeKey);
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: '操作失败'
                                    });
                                }
                            })
                            // this.websocket.send(JSON.stringify({ Data: lJSONObject_DataSet, Action: 'BatchPoints', AccessToken: getCookie('token') }));
                        } else {
                            this.$message({
                                type: 'error',
                                message: '操作失败'
                            });
                        }
                    }, complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    }
                });
            } else {
                if (this.multipleSelection.length == 0) {
                    this.$message({
                        type: 'warning',
                        message: '请选择发放（取消发放）积分的人员'
                    });
                    return
                }
                this.$confirm('此操作将' + (is == '1' ? '给该参与成员发放积分' : '取消给该成员发放积分') + '是否继续', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    let str1 = this.multipleSelection.map(i => `'${i.Village_Activity_Member_SerialNumber}'`).join(',');
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        method: "post",
                        data: {
                            Data: 'village_activities_members',
                            Condition: `Village_Activity_Member_SerialNumber IN (${str1})`
                        },
                        success: (village_activities_members) => {
                            if (village_activities_members.length > 0) {
                                village_activities_members.forEach(item => {
                                    item.isPoints = is
                                })

                                let lJSONObject_DataSet = {
                                    Modify: {
                                        village_activities_members,
                                    },
                                    Add: {}
                                };
                                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                    Operation_Type: '0',
                                    Operation_Path: this.relativePath,
                                    Operation_Main,
                                    Operation_Interface: "generalSave",
                                    Operation_IP: getIpAddress()
                                }]
                                console.log(lJSONObject_DataSet);
                                submitSave(lJSONObject_DataSet,(res)=>{
                                    if (res.Status == 'success') {
                                        this.$refs.multipleTable.clearSelection();
                                        this.isPoints = false;
                                        if (this.$refs.ylUpload) {
                                            this.$refs.ylUpload.handleClear();
                                        }
                                        this.personal_points_change_log_attachment = [];
                                        this.showDialog1 = false;
                                        this.handleShow(this.nodeKey);
                                    } else {
                                        this.$message({
                                            type: 'error',
                                            message: '操作失败'
                                        });
                                    }
                                })
                                // this.websocket.send(JSON.stringify({ Data: lJSONObject_DataSet, Action: 'BatchPoints', AccessToken: getCookie('token') }));
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '操作失败'
                                });
                            }
                        }, complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        }
                    });
                }).catch(() => { });
            }
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                if (this.is) {
                    this.village_activities.Activity_isEdit = '1'
                    let lJSONObject_DataSet = {
                        Modify: {
                            village_activities_members: [this.form],
                            village_activities: [this.village_activities]
                        }
                    }
                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    if (!lJSONObject_DataSet['Add']) {
                        lJSONObject_DataSet['Add'] = new Object();
                    }
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0',
                        Operation_Path: this.relativePath,
                        Operation_Main,
                        Operation_Interface: "generalSave",
                        Operation_IP: getIpAddress()
                    }]
                    submitSave(lJSONObject_DataSet,(res)=>{
                        this.handleShow(this.nodeKey);
                        if (res.Status == 'success') {
                            
                            this.form.Check_In_Datetime = '';
                            this.showDialog = false;
                        }
                    })
                    // this.websocket.send(JSON.stringify({ Data: lJSONObject_DataSet, Action: 'QianDao', AccessToken: getCookie('token') }));
                } else {
                    let str1 = this.multipleSelection.map(i => `'${i.Village_Activity_Member_SerialNumber}'`).join(',');
                    let str2 = this.multipleSelection.map(i => `'${i.Village_Activity_SerialNumber}'`).join(',');
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                        method: "post",
                        data: {
                            Data: JSON.stringify([{
                                tableName: 'village_activities_members',
                                Condition: window.btoa(unescape(encodeURIComponent(`Village_Activity_Member_SerialNumber IN (${str1})`))),
                            }, {
                                tableName: 'village_activities',
                                Condition: window.btoa(unescape(encodeURIComponent(`Village_Activity_SerialNumber IN (${str2})`))),
                            }])
                        },
                        success: ({ village_activities_members, village_activities }) => {
                            village_activities.forEach(item => {
                                item.Activity_isEdit = '1'
                            })
                            village_activities_members.forEach(item => {
                                item.Check_In_Datetime = this.form.Check_In_Datetime;
                                item.Picture_URL = this.form.Picture_URL;
                            })

                            let lJSONObject_DataSet = {
                                Modify: {
                                    village_activities_members,
                                    village_activities,
                                }
                            };
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            if (!lJSONObject_DataSet['Add']) {
                                lJSONObject_DataSet['Add'] = new Object();
                            }
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSave",
                                Operation_IP: getIpAddress()
                            }]
                            submitSave(lJSONObject_DataSet,(res)=>{
                                this.handleShow(this.nodeKey);
                                if (res.Status == 'success') {
                                    // this.handleShow(this.nodeKey);
                                    this.form.Check_In_Datetime = '';
                                    this.form.Picture_URL = '';
                                    this.showDialog = false;
                                }
                            })
                            // this.websocket.send(JSON.stringify({ Data: lJSONObject_DataSet, Action: 'QianDao', AccessToken: getCookie('token') }));
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                    });
                }
            }

        },
        handleShow(nodeKey) {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: "t_village_activities_members",
                    Condition: window.btoa(unescape(encodeURIComponent(nodeKey))),
                },
                success: (res) => {
                    this.Data = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'village_activities',
                    Condition: `Village_Activity_SerialNumber='${nodeKey}'`,
                },
                success: (res) => {
                    if (res.length == 1) {
                        if (+new Date() > +new Date(res[0].Activity_Datetime)) {
                            this.isDK = true
                        }
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        batchSign() {
            if (!this.isDK) {
                this.$message({
                    type: 'warning',
                    message: '活动未开始'
                });  
                return 
            }
            if (this.multipleSelection.length > 0) {
                this.is = false;
                this.showDialog = true;
            } else {
                this.$message({
                    type: 'warning',
                    message: '请选择要签到的人员'
                });
            }

        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        selectable(row) {
            if (this.isPoints) {
                return row.isPoints == '0';
            } else {
                return row.Check_In_Datetime == '';
            }
        },
        goBack() {
            window.history.back();
        },
    },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.component('yl-upload', ylUpload);
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
